package com.strawcom.charmring.ui;

import android.content.ContentValues;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.*;
import android.widget.AdapterView.OnItemClickListener;
import com.android.volley.Request.Method;
import com.strawcom.charmring.BaseActivity;
import com.strawcom.charmring.C;
import com.strawcom.charmring.R;
import com.strawcom.charmring.bean.Friend;
import com.strawcom.charmring.bean.http.BaseResponse;
import com.strawcom.charmring.bean.http.PostEmergencyConfigRequest;
import com.strawcom.charmring.util.HttpUtil;
import com.strawcom.charmring.util.HttpUtil.ResponeListener;
import com.strawcom.charmring.util.LogUtil;
import com.strawcom.charmring.util.PreferenceUtil;
import com.strawcom.charmring.view.TitleView;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

public class AlarmActivity extends BaseActivity implements OnClickListener,OnItemClickListener{

	private TitleView titleView;
	private Button btnContact;
	private ListView listView;
	private final int requestCode_add=1;
	private final int requestCode_delete=2;
	private List<ContentValues> selectContacts=new ArrayList<ContentValues>();
	private LayoutInflater inflater;
	private EditText editAlarm;
	private static final String NAME = "name", NUMBER = "number";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.activity_alarm);
		super.onCreate(savedInstanceState);
		initView();
		
		findViewById(R.id.layout_content).setOnClickListener(new OnClickListener() {
			@Override public void onClick(View v) {
				closeInputMethod();
			}
		});
	}

	private void initView() {
		inflater=LayoutInflater.from(this);
		
		titleView = (TitleView) findViewById(R.id.title_view);
		titleView.setTitleText(R.string.title_alarm);
		
		btnContact=(Button) findViewById(R.id.btn_contact);
		btnContact.setOnClickListener(this);
		
		editAlarm=(EditText) findViewById(R.id.edit_alarm);
		String alarmMsg=PreferenceUtil.readString(this, C.sp.alarm_msg_info,"");
			if(!"".equals(alarmMsg)){
				PostEmergencyConfigRequest configRequest=HttpUtil.gson.fromJson(alarmMsg, PostEmergencyConfigRequest.class);
				if(configRequest.contactlist!=null && configRequest.contactlist.size()>0){
					for (int i = 0; i < configRequest.contactlist.size(); i++) {
						ContentValues contentValues=new ContentValues();
						contentValues.put(NAME, configRequest.contactlist.get(i).name);
						contentValues.put(NUMBER, configRequest.contactlist.get(i).phone);
						selectContacts.add(contentValues);
					}
				}
				editAlarm.setText(configRequest.msg);
			}
		listView=(ListView) findViewById(R.id.list_view);
		listView.setAdapter(adapter);
		listView.setOnItemClickListener(this);
		
	}
	

	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.btn_contact:
			Intent intent=new Intent(AlarmActivity.this,ContactActivity.class);
			intent.putExtra("list", (Serializable)selectContacts);
			startActivityForResult(intent,requestCode_add);
			break;
		default:
			break;
		}
	}
	
	@Override
	public void onItemClick(AdapterView<?> adapterView, View view, int poistion, long id) {
		Intent intent=new Intent(this,ContactInfoActivity.class);
		intent.putExtra("contactInfo", selectContacts.get(poistion));
		intent.putExtra("poistion", poistion);
		startActivityForResult(intent, requestCode_delete);
	}

	
	protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
		if(requestCode==requestCode_add&&resultCode==RESULT_OK){
			selectContacts.clear();
			@SuppressWarnings("unchecked")
			List<ContentValues> list=(List<ContentValues>)intent.getSerializableExtra("list");
			selectContacts.addAll(list);
			adapter.notifyDataSetChanged();
		}else if(requestCode==requestCode_delete&&resultCode==RESULT_OK){
			int poistion=intent.getIntExtra("poistion", -1);
			if(poistion>=0){
				selectContacts.remove(poistion);
				adapter.notifyDataSetChanged();
			}
		}
	};
	
	public void onBackPressed() {
		super.onBackPressed();
		if(selectContacts == null || selectContacts.size()  < 1) {
			LogUtil.d("empty contacts, do not upload");
			return;
		}
		
		String messageInfo = editAlarm.getText().toString();
		if(TextUtils.isEmpty(messageInfo)){
			messageInfo = editAlarm.getHint().toString();
		}
			final PostEmergencyConfigRequest configRequest=new PostEmergencyConfigRequest();
			configRequest.msgid=C.request_msgid_post_emergency_config;
			List<Friend> list=new ArrayList<Friend>();
			for (int i = 0; i < selectContacts.size(); i++) {
				Friend info=new Friend();
				String countryText = PreferenceUtil.readString(this, C.sp.phone_ex);
				String phone = selectContacts.get(i).getAsString(NUMBER);
				if (!phone.startsWith(countryText)) {
					info.phone = countryText + phone;
				}

				info.phone = info.phone.replace(" ", "");
				info.name = selectContacts.get(i).getAsString(NAME);
				list.add(info);
			}
			
			configRequest.contactlist = list;
			configRequest.msg=messageInfo;
			HttpUtil.requestJson(Method.POST, configRequest, new ResponeListener() {
				
				@Override
				public void onResponse(BaseResponse response, String resultStr) {
					if(0 == response.retcode) {
						PostEmergencyConfigRequest without86 = new PostEmergencyConfigRequest();
						String countryText = PreferenceUtil.readString(AlarmActivity.this, C.sp.phone_ex);
						without86.msg = configRequest.msg;
						without86.contactlist = new ArrayList<Friend>();
						for (Friend f : configRequest.contactlist) {
							if (f.phone != null && f.phone.startsWith(countryText)) {
								f.phone = f.phone.substring(countryText.length());
							}
							without86.contactlist.add(f);
						}
						String ci = HttpUtil.gson.toJson(without86);
						PreferenceUtil.write(AlarmActivity.this, C.sp.alarm_msg_info, ci);
					}
				}
				
				@Override
				public void onErrorResponse(Exception error) {
					LogUtil.d("联系人设置失败 -- "+error.getMessage());
				}
			});
		
		
	};
	
	BaseAdapter adapter=new BaseAdapter() {
		
		@Override
		public View getView(int poistion, View contentView, ViewGroup group) {
			ViewHolder holder=null;
			if(contentView==null){
				contentView=inflater.inflate(R.layout.item_alarm_contact, null);
				holder=new ViewHolder();
				holder.name=(TextView) contentView.findViewById(R.id.name);
				holder.number=(TextView) contentView.findViewById(R.id.number);
				contentView.setTag(holder);
			}else{
				holder=(ViewHolder) contentView.getTag();
			}
			holder.name.setText(selectContacts.get(poistion).getAsString(NAME));
			String number = selectContacts.get(poistion).getAsString(NUMBER);
			String countryText = PreferenceUtil.readString(AlarmActivity.this, C.sp.phone_ex);
			number = number.replace(" ", "");

			if (number.startsWith(countryText)) {
				number = number.substring(countryText.length());
			}
			if (number.startsWith("+"+countryText)) {
				number = number.substring(countryText.length() + 1);
			}
			System.out.println(number);
			holder.number.setText(number);
			return contentView;
		}
		
		@Override
		public long getItemId(int id) {
			return id;
		}
		
		@Override
		public Object getItem(int poistion) {
			return selectContacts.get(poistion);
		}
		
		@Override
		public int getCount() {
			return selectContacts.size();
		}
	};
	
	class ViewHolder{
		TextView name;
		TextView number;
	}

}
